package com.woniu.filter;

import com.woniu.uitl.JwtTokenUitl;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * token全局过滤器
 */

@Component
@Order(0)
public class CustomGlobalFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> strings = exchange.getRequest().getHeaders().get("tokenStr");
        if (!StringUtils.isEmpty(strings)){
           if (JwtTokenUitl.checkSign(strings.get(0))){
               //执行微服务并且回调
                return chain.filter(exchange).then(Mono.fromRunnable(new Runnable() {
                    @Override
                    public void run() {
                        HttpStatus statusCode = exchange.getResponse().getStatusCode();
                        if (statusCode.value() == 500){
                            throw new RuntimeException("500:服务器繁忙");
                        }else if (statusCode.value() == 404){
                            throw new RuntimeException("404:地址非法");
                        }else if (statusCode.value() == 400){
                            throw new RuntimeException("400:参数错误");
                        }else if (statusCode.value() == 405){
                            throw new RuntimeException("405:请求方式错误");
                        }
                    }
                }));
           }else {
               String jsonStr = "{\"status\":\"400\", \"msg\":\"token非法\"}";
               byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
               DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
               return exchange.getResponse().writeWith(Flux.just(buffer));
           }

        }else {
            String jsonStr = "{\"status\":\"400\", \"msg\":\"token为空\"}";
            byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Flux.just(buffer));
        }
    }
}
